package ai.people.core.webhook.feishu.aspect;

import ai.people.core.common.util.ApplicationContextUtil;
import ai.people.core.webhook.entity.ErrorInfo;
import ai.people.core.webhook.feishu.utils.FeishuWebhookMsg;
import ai.people.core.common.util.IpAddressUtil;
import ai.people.netmon.utils.NumeralPool;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhenglin
 * @date 2022/5/18
 */
@Aspect
@Component
@Slf4j
public class MsgAspect {

    @Autowired(required = false)
    FeishuWebhookMsg feishuWebhookMsg;

    RestTemplate restTemplate;

    @Autowired
    public void setRestTemplate() {
        this.restTemplate = ApplicationContextUtil.getBean(RestTemplate.class);
    }

//    @Pointcut("execution(* *..controller..*(..))")
//    public void sendMsgPointcut() {
//    }

    @Pointcut("execution(* ai.people.core.web.exception.handler..*(..))")
    public void webExceptionPointcut() {
    }

//    @AfterThrowing(value = "sendMsgPointcut()", throwing = "throwable")
//    public void doAfterThrowing(Throwable throwable) throws Throwable {
//        if (feishuWebhookMsg == null){
//            log.error("feishuWebhookMsg is null please check config");
//            return;
//        }
//
//        handle(throwable);
//    }

    private void handle(Throwable throwable) {
        String title = throwable.getMessage() == null ? "服务器错误" : throwable.getMessage();

        StackTraceElement[] stackTrace = throwable.getStackTrace();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < NumeralPool.FIFTEEN && i < stackTrace.length; i++) {
            sb.append(stackTrace[i].toString()).append("\n");
        }
        sb.append("...\n详情堆栈信息请查看日志");
        String stackInfo = sb.toString();

        ErrorInfo errorInfo = new ErrorInfo();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        //LogInfo logInfo = LogInfoThreadLocal.get();
        //if (logInfo != null) {
            errorInfo.setErrMsgTitle(title);
            errorInfo.setErrStackTrace(stackInfo);
            errorInfo.setRequestIp(IpAddressUtil.getIpAddress(request));
            errorInfo.setRequestUrl(request.getRequestURI());
            errorInfo.setRequestMethod(request.getMethod());
            //errorInfo.setRequestJson(logInfo.getJsonStringParams());
        //}else {
        //    errorInfo.setErrMsgTitle(title);
        //    errorInfo.setErrStackTrace(stackInfo);
        //}
        feishuWebhookMsg.send(restTemplate, errorInfo);
    }


    @Before(value = "webExceptionPointcut()")
    public void before(JoinPoint joinPoint) throws Throwable {
        if (feishuWebhookMsg == null){
            log.error("feishuWebhookMsg is null please check config");
            return;
        }
        Throwable throwable = (Throwable) joinPoint.getArgs()[0];
        handle(throwable);
    }

}
